'use strict';

const Service = require('egg').Service;

class BaseService extends Service {
  /**
   * @param {import('egg').Context} ctx
   * @param {import('sequelize').Model} model
   */
  constructor(ctx, model) {
    super(ctx);
    this.model = model;
  }

  async list(where = {}, options = {}) {
    const rows = await this.model.findAll({
      where,
      order: [['updated_at', 'DESC']],
      ...options,
    });
    return rows;
  }

  async findById(id) {
    return await this.model.findByPk(id);
  }

  async create(data) {
    const created = await this.model.create(data);
    return created;
  }

  async updateById(id, data) {
    const [affected] = await this.model.update(data, { where: { id } });
    return affected; // 返回影响行数
  }

  async deleteById(id) {
    const affected = await this.model.destroy({ where: { id } });
    return affected; // 返回删除行数
  }
}

module.exports = BaseService;